/* vim: set ts=2 et sw=2 cindent fo=qroca: */

package com.globant.google.mendoza.command;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.globant.google.mendoza.MendozaServer;
import com.globant.google.mendoza.MendozaRequest;
import com.globant.google.mendoza.MendozaServerState;
import com.globant.google.mendoza.malbec.BuyerGiftCertificate;

/** Represents the mendoza add gift certificate command.
 */
public final class MendozaAddGiftCommand extends MendozaBaseCommand {

  /** The class logger.
   */
  private static Log log = LogFactory.getLog(MendozaAddGiftCommand.class);

  /** The Gift certificate code label. */
  private final String giftCertificateCodeLabel = "Gift certificate code";

  /** Creates an instance of MendozaLoginCommand.
   *
   * @param mendozaRequest The mendoza server request.
   *
   * @param mendoza The mendoza server.
   *
   * @param mendozaState The mendoza server state.
   */
  public MendozaAddGiftCommand(
      final MendozaRequest mendozaRequest, final MendozaServer mendoza,
      final MendozaServerState mendozaState) {
    super(mendozaRequest, mendoza, mendozaState);
    setName("Add gift certificate");
  }

  /** Executes the mendoza server add gift
   * certificate command.
   */
  public void execute() {
    log.trace("Entering execute");
    MendozaCommandResult result = new MendozaCommandResult();
    String commandResultMsg =
        "OK - Add gift certificate command sent to the mendoza server.";
    try {
      setRequestParameters();
      result.setSuccess(commandResultMsg);
    } catch (RuntimeException e) {
      commandResultMsg = e.getMessage();
      result.setError(commandResultMsg);
    }
    setResult(result);
    logCommand(this);
    log.trace("Leaving execute");
  }

  /** Sets the login command parameters.
   */
  private void setRequestParameters() {
    log.trace("Entering setRequestParameters");
    String giftCode =
      getMendozaRequest().getRequestParameters().getProperty("code");
    if (giftCode == null) {
      log.trace("Leaving setRequestParameters");
      throw new RuntimeException("The gift certificate code cannot be null");
    }
    getMendozaState().addGiftCertificate(new BuyerGiftCertificate(giftCode));
    logRequestParameter(giftCertificateCodeLabel, giftCode);
    log.trace("Leaving setRequestParameters");
  }
}

